package com.foreverwin.mes.lims.controller;

import com.foreverwin.mes.common.enums.HandleEnum;
import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.lims.model.BadEntryOfWorkshopMate;
import com.foreverwin.mes.lims.model.DefeRecodesOfWorkInProc;
import com.foreverwin.mes.lims.service.BadEntryOfWorkshopMateService;
import com.foreverwin.mes.lims.service.DefeRecodesOfWorkInProcService;
import com.foreverwin.mes.lims.util.NowString;
import com.foreverwin.mes.production.dto.SfcInWorkDto;
import com.foreverwin.mes.production.service.SfcExService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.foreverwin.mes.lims.service.UnplannedSamplingService;
import com.foreverwin.mes.lims.model.UnplannedSampling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Mark
 * @since 2020-03-11
 */
@Controller
@RequestMapping("/unplannedSamplings")
public class UnplannedSamplingController {
    private final Logger logger = LoggerFactory.getLogger(UnplannedSamplingController.class);

    private final Boolean isLocalTest = true;

    @Autowired
    public UnplannedSamplingService unplannedSamplingService;

    @Autowired
    public DefeRecodesOfWorkInProcService defeRecodesOfWorkInProcService;

    @Autowired
    public SfcExService sfcExService;

    @Autowired
    public BadEntryOfWorkshopMateService badEntryOfWorkshopMateService;

    /**
    * 根据id查询
    *
    * @param id 主键
    * @return
    */
    @ResponseBody
    @GetMapping("/{id:.+}")
    public AjaxResult getUnplannedSamplingById(@PathVariable String id) {
        UnplannedSampling result;
        try {
            result = unplannedSamplingService.selectById(id);
        } catch (Exception e) {
            logger.error("getUnplannedSamplingById -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getUnplannedSamplingList(UnplannedSampling unplannedSampling){
        List<UnplannedSampling> result;
        try {
            EntityWrapper<UnplannedSampling> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(unplannedSampling);
            result = unplannedSamplingService.selectList(EntityWrapper);
        } catch (Exception e) {
            logger.error("getUnplannedSamplingList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 分页查询数据
     *
     * @param frontPage  分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getUnplannedSamplingPageList")
    public AjaxResult getUnplannedSamplingPageList(FrontPage<UnplannedSampling> frontPage, UnplannedSampling unplannedSampling){
        Page result;
        try {
            String site = CommonMethods.getSite();
            unplannedSampling.setSite(site);
            EntityWrapper<UnplannedSampling> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(unplannedSampling);
            if (frontPage.getGlobalQuery() != null && !"".equals(frontPage.getGlobalQuery().trim())) {
                //TODO modify global query
                EntityWrapper
                    .like("handle", frontPage.getGlobalQuery())
                    .or().like("site", frontPage.getGlobalQuery())
                    .or().like("resource", frontPage.getGlobalQuery())
                    .or().like("resoDesc", frontPage.getGlobalQuery())
                    .or().like("operation", frontPage.getGlobalQuery())
                    .or().like("sampBatch", frontPage.getGlobalQuery())
                    .or().like("item", frontPage.getGlobalQuery())
                    .or().like("itemName", frontPage.getGlobalQuery())
                    .or().like("measUnit", frontPage.getGlobalQuery())
                    .or().like("creator", frontPage.getGlobalQuery())
                    .or().like("updater", frontPage.getGlobalQuery())
        ;
            }
            result = unplannedSamplingService.selectPage(frontPage.getPagePlus(), EntityWrapper);
        } catch (Exception e) {
            logger.error("getUnplannedSamplingPageList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 保存和修改公用
     * @param unplannedSampling  传递的实体
     * @return  null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_save")
    public AjaxResult unplannedSamplingSave(@RequestBody UnplannedSampling unplannedSampling) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        //------------------------------------------------------------------------------------------------------------
        String resource = unplannedSampling.getResource();
        String sampBatch = unplannedSampling.getSampBatch();

        String nowStr = NowString.NowString();
        Timestamp nowTs = Timestamp.valueOf(nowStr);
        String handle = HandleEnum.DEFECTIVE_RECORDS_OF_WIP.getHandle( unplannedSampling.getSite(), resource, sampBatch);
        unplannedSampling.setHandle(handle);
        unplannedSampling.setCreatedDateTime(nowTs);
        unplannedSampling.setModifiedDateTime(nowTs);
        int count;
        try {
            count = unplannedSamplingService.insertOrUpdate(unplannedSampling) ? 1 : 0;
        } catch (Exception e) {
            logger.error("unplannedSamplingSave -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(count == 0 ? null : unplannedSampling);
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:.+}")
    public AjaxResult unplannedSamplingDelete(@PathVariable("id") String id){
        int count;
        try {
            count = unplannedSamplingService.deleteById(id) ? 1 : 0;
        } catch (Exception e) {
            logger.error("unplannedSamplingDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 批量删除对象
     * @param ids 实体集合ID
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_batchDelete")
    public AjaxResult removeByIds(List<String> ids){
        int count;
        try {
            count = unplannedSamplingService.deleteBatchIds(ids) ? 1 : 0;
        } catch (Exception e) {
            logger.error("unplannedSamplingBatchDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 通过site查询：设备、设备描述、工序
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getResource")
    public AjaxResult getResource(UnplannedSampling unplannedSampling){
        String site = CommonMethods.getSite();
        DefeRecodesOfWorkInProc defeRecodesOfWorkInProc = new DefeRecodesOfWorkInProc();
        defeRecodesOfWorkInProc.setSite(site);
        List<DefeRecodesOfWorkInProc> result;
        try {

            result = defeRecodesOfWorkInProcService.getResourceAndOperation(defeRecodesOfWorkInProc);

        } catch (Exception e) {
            logger.error("getResource -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询：留样批次、物料编号、物料名称、单位
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getSampleBatch")
    public AjaxResult getSampleBatch(UnplannedSampling unplannedSampling){
        ArrayList<UnplannedSampling> result = new ArrayList<UnplannedSampling>();
        String site = CommonMethods.getSite();
//===================在制批次开始==================================================================================================================
        //----------------本地测试数据Start-----------------------------------------------------------------------------------------------
        if(isLocalTest) {
            for(int i=0;i<4;i++){
                UnplannedSampling ins = new UnplannedSampling();
                String resource = "200000"+i;
                String retentionSampleBatch = "P20191012_SFC00000"+i;
                String item = "030301001"+i;
                String itemName = "奶泡胶囊袋装-D#"+i;
                String measureUnit = "BAG#"+i;

                ins.setResource(resource);
                ins.setSampBatch(retentionSampleBatch);
                ins.setItem(item);
                ins.setItemName(itemName);
                ins.setMeasUnit(measureUnit);

                result.add(ins);
            }
            if( unplannedSampling.getResource()!=null ) {
                for (int l = 0; l < result.size(); l++) {
                    UnplannedSampling ins = result.get(l);
                    if (!unplannedSampling.getResource().equals(ins.getResource())) {
                        result.remove(l);
                        l--;
                    }
                }
            }
        }else{
            List<SfcInWorkDto> sfcInWorkDtoList;
            try {
                sfcInWorkDtoList = sfcExService.listSfcInWork(site, unplannedSampling.getResource(), "", "");
            } catch (Exception e) {
                return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
            }
            //---------------------------------------------------------------------------------------------------------------
            for(int i=0;i<sfcInWorkDtoList.size();i++){
                UnplannedSampling ins = new UnplannedSampling();
                SfcInWorkDto sfcInWorkDto = sfcInWorkDtoList.get(i);
                String sfcBatch = sfcInWorkDto.getSfc();
                String item = sfcInWorkDto.getItem();
                String itemName = sfcInWorkDto.getItemDescription();
                String measureUnit = sfcInWorkDto.getUnitOfMeasure();
                String qtyInWork = sfcInWorkDto.getQtyInWork();

                ins.setSampBatch(sfcBatch);
                ins.setItem(item);
                ins.setItemName(itemName);
                ins.setMeasUnit(measureUnit);
                ins.setSampQty(Long.parseLong(qtyInWork));
                result.add(ins);
            }
        };
//===================在制批次结束==================================================================================================================
//===================库存批次开始==================================================================================================================
        List<UnplannedSampling> result_i =unplannedSamplingService.selectInventoryBatch(unplannedSampling);
//===================库存批次结束==================================================================================================================
//===================合并在制及库存批次开始==================================================================================================================
         for( int l=0;l<result_i.size();l++ ){
             result.add(result_i.get(l));
        }
//===================合并在制及库存批次结束==================================================================================================================


        return AjaxResult.success(result);
    }
}